package com.tiantianyuegou.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.R;
import com.tiantianyuegou.adapter.QiangGouAdapter;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.model.Ad;
import com.tiantianyuegou.model.OneGouModle;
import com.tiantianyuegou.model.QiangGouModel;
import com.tiantianyuegou.util.Tools;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 一元购详情
 */
public class OneGouGoodsDetail extends BaseActivity implements View.OnClickListener{
    private TextView tv_goodsname,tv_count,tv_goods_detial,tv_end_time,tv_qiang;
    private ListView lv;
    private String TAG = "OneGouGoodsDetail";
    private List<Ad> adlist = new ArrayList<Ad>();
    private LinearLayout linearDot;
    private ImageView ADtips[];//图片的数组
    private ViewPager adv_viewpage;
    private int ADCurrentPage = 0;//当前页码
    private BitmapUtils bitmapUtils;
    private Context context;
    private ListView listView;
    private List<QiangGouModel> mod = new ArrayList<>();
    QiangGouAdapter adapter;
    String goodsStart,endTime,count,goodsId,goodsName;
    private MyCount myCount;
    private Button btn_goumai;
    private OneGouModle oneModel;
    private String goodsMoney;
    private String goodsPhoto;
    private String jifen;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one_gou_goods_detail);
        context = OneGouGoodsDetail.this;
        Tools.changeSystemBar(this);
        setTitle("一元购详情");
        initViews();
        loadAdv();
        bitmapUtils = new BitmapUtils(context);
        Log.e("传递的商品的id是", goodsId+goodsStart+endTime+goodsName+ count+ "获取到传递的数据是");
        myCount = new MyCount(OneGouGoodsDetail.this,Long.parseLong(endTime), 1000);
        myCount.start();

    }

    @Override
    public void findViewByIds() {
        btn_goumai = (Button) findViewById(R.id.btn_goumai);
        tv_goodsname = (TextView) findViewById(R.id.tv_goodsname);
        tv_count = (TextView) findViewById(R.id.tv_count);
        tv_goods_detial = (TextView) findViewById(R.id.tv_goods_detial);
        tv_end_time = (TextView) findViewById(R.id.tv_end_time);
        tv_qiang = (TextView) findViewById(R.id.tv_qiang);
        linearDot = (LinearLayout) findViewById(R.id.dot);
        lv = (ListView) findViewById(R.id.lv);
        adv_viewpage = (ViewPager) findViewById(R.id.vp_adv);
        adapter = new QiangGouAdapter(this);
        lv.setAdapter(adapter);
    }

    @Override
    public void initListener() {
        tv_goods_detial.setOnClickListener(this);
        btn_goumai.setOnClickListener(this);


    }
    @Override
    public void initData() {
        //        获取传入的数据并设置到页面上
        Intent intent = getIntent();
         oneModel = (OneGouModle) intent.getSerializableExtra("oneModel");
        goodsStart = oneModel.getGoodsStart();
        endTime = intent.getStringExtra("endTime");//结束倒计时
        goodsName = intent.getStringExtra("goodsName");//商品名称
        count = intent.getStringExtra("count");//剩余人数
        goodsId = intent.getStringExtra("goodsId");//商品id
         goodsMoney = intent.getStringExtra("goodsMoney");//商品价格
         goodsPhoto = intent.getStringExtra("goodsPhoto");//商品图片
         jifen = intent.getStringExtra("jifen");//积分抵换
        tv_goodsname.setText(goodsName);
        tv_count.setText(count);
        //mill为你龙类型的时间戳
        Date date=new Date(Long.parseLong(endTime));
        String strs = "";
        try {
            //yyyy表示年MM表示月dd表示日
            //yyyy-MM-dd是日期的格式，比如2015-12-12如果你要得到2015年12月12日就换成yyyy年MM月dd日
            SimpleDateFormat sdf=new SimpleDateFormat("HH:mm");
            //进行格式化
            strs =sdf.format(date);
            System.out.println(strs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        tv_end_time.setText(strs);

//        抢购记录   http://hjtech.wicp.net:8080/tiantianyuegou-api/one/in?topId=1
        RequestParams params = new RequestParams();
        params.addBodyParameter("topId",goodsId);
        Log.e("传递的商品的id是", goodsId+goodsStart+endTime+goodsName+ count+ "获取到传递的数据是");
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.QIANG_GOU, params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        Log.e(TAG, "请求抢购记录列表数据" + responseInfo.result);
                        try {
                            JSONObject object = new JSONObject(responseInfo.result);
                            String code = object.optString("code");
                            if (code.equalsIgnoreCase("100")){
                                JSONArray array = object.optJSONArray("list");
                                mod.clear();
                                for (int i = 0; i <array.length() ; i++) {
                                    QiangGouModel moo = new QiangGouModel();
                                    JSONObject obj = array.optJSONObject(i);
                                    String gouId = obj.optString("tm_id");
                                    String gouName = obj.optString("tm_name");
                                    String mobile = obj.optString("tm_mobile");
                                    long time = obj.optLong("ti_addtime");
                                    moo.setGouName(gouName);
                                    moo.setMobile(mobile);
                                    moo.setTime(time);
                                    mod.add(moo);
                                }
                                if (mod.size()==0){
                                    tv_qiang.setVisibility(View.VISIBLE);
                                }else {
//                                设置适配器为lv
                                lv.setAdapter(adapter);
                                adapter.setData(mod);
                                adapter.notifyDataSetChanged();
                                Log.e(TAG, "获取到抢购记录的集合的长度是"+mod.size() + "");
                                }

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFailure(HttpException e, String s) {

                    }
                }

        );

    }
    /**
     * 加载轮播图
     */
    public void loadAdv() {

        RequestParams params = new RequestParams();
        params.addBodyParameter("tacCataId", 1+"");
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.HOME_ADV_LIST, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                Log.e(TAG, "onSuccess response.result" +
                        response.result);
                if (TextUtils.isEmpty(response.result)) {
                    showMsg("加载轮播图失败");
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            JSONArray result = jsonObject.getJSONArray("list");
                            if (result.length() > 0) {
                                adlist.clear();
                                for (int i = 0; i < result.length(); i++) {
                                    JSONObject temp = result.getJSONObject(i);
                                    String tacId = temp.getString("tacId");
                                    String tacPhoneImage = temp.getString("tacPhoneImage");
                                    String tacLink = temp.getString("tacLink");

                                    Ad adImage = new Ad(tacId, tacPhoneImage, tacLink);
                                    adlist.add(adImage);

                                }
                                changeAdv();
                                Log.e(TAG, adlist.size() + "sadsadasd");
                            }

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });

    }

    public void changeAdv() {
        ADtips = new ImageView[adlist.size()];
        for (int i = 0; i < ADtips.length; i++) {
            ImageView img = new ImageView(OneGouGoodsDetail.this);
            LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(20, 20);
            ADtips[i] = img;
            if (i != 0) {
                layoutParam.leftMargin = 5;
                img.setBackgroundResource(R.mipmap.homead_nochoose);//黑色背景
            } else {
                img.setBackgroundResource(R.mipmap.homead_choose);// 蓝色背景
            }
            linearDot.addView(img, layoutParam);
        }
        // 通过适配器引入图片
        MyViewPager mAdapter = new MyViewPager(OneGouGoodsDetail.this, adlist);
        adv_viewpage.setAdapter(mAdapter);
        adv_viewpage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                ADtips[ADCurrentPage]
                        .setBackgroundResource(R.mipmap.homead_nochoose);
                ADCurrentPage = position;
                ADtips[position]
                        .setBackgroundResource(R.mipmap.homead_choose);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        // 计时器
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ADtips[ADCurrentPage]
                                .setBackgroundResource(R.mipmap.homead_nochoose);
                        if (ADCurrentPage == ADtips.length - 1) {
                            ADCurrentPage = 0;
                        } else {
                            ADCurrentPage++;
                        }
                        ADtips[ADCurrentPage]
                                .setBackgroundResource(R.mipmap.homead_choose);
                        adv_viewpage
                                .setCurrentItem(ADCurrentPage);
                    }
                });
            }
        }, 5000, 5000);
        // 轮播图结束
    }

    //    图片数组
    String[] imageViews = { "http://www.zgttyg.com/tiantianyuegou-gm/upload/project/20160912173803_0.jpg", "http://www.zgttyg.com/tiantianyuegou-gm/upload/project/20160905120000_3.jpg",
            " http://www.zgttyg.com/tiantianyuegou-gm/upload/project/20160905115937_0.jpg"};

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_goods_detial:
//                当点击商品详情时跳转到商品详情界面
                break;
            case R.id.btn_goumai:
//                TODO 代做页面跳转
//                当点击按钮的时候跳转到确认订单界面,当支付完成之后跳转到添加一元购界面
//                当点击立即购买跳转到选择地址，然后在跳转到支付界面，然后在跳转到添加一元购界面
                Intent intent = new Intent(OneGouGoodsDetail.this, OneGouConfirmOrderActivity.class);
//                将商品tbId进行传递,商品名称，剩余人数，价钱，商品图片，积分比例进行传递
                intent.putExtra("goodsName",goodsName);//商品名称
                intent.putExtra("count",count);//剩余量
                intent.putExtra("goodsMoney",goodsMoney);//商品价钱
                intent.putExtra("goodsPhoto",goodsPhoto);//商品图片
                intent.putExtra("jifen",jifen);//积分抵换


                startActivity(intent);
                break;
        }
    }

    class MyViewPager extends PagerAdapter{
        private Context context;
        private List<Ad> data = new ArrayList<>();

        public MyViewPager(Context context, List<Ad> data) {
            this.context = context;
            this.data = data;
            bitmapUtils = new BitmapUtils(OneGouGoodsDetail.this);
        }

        @Override
        public int getCount() {
            return imageViews.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
//            将view添加到container中并将view给返回
            View view = View.inflate(OneGouGoodsDetail.this, R.layout.adapter, null);
            ImageView imageView = (ImageView) view.findViewById(R.id.img);
            bitmapUtils.display(imageView,imageViews[position]);
//            将请求到的图片添加到viewpager中
//            ImageLoader.getInstance().displayImage(imageViews[position], imageView);
            Log.e("图片的地址是========",imageViews[position]);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            super.destroyItem(container, position, object);
            container.removeView((View) object);
        }
    }

  /*  *//**
     * 加载轮播图
     *//*
    public void loadAdv() {
//        一元购商品图片轮播图
        RequestParams params = new RequestParams();
        params.addBodyParameter("tacCataId", 1+"");
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.HOME_ADV_LIST, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });

    }

    public void changeAdv() {
        ADtips = new ImageView[adlist.size()];
        for (int i = 0; i < ADtips.length; i++) {
            ImageView img = new ImageView(context);
            LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(20, 20);
            ADtips[i] = img;
            if (i != 0) {
                layoutParam.leftMargin = 5;
                img.setBackgroundResource(R.mipmap.homead_nochoose);//黑色背景
            } else {
                img.setBackgroundResource(R.mipmap.homead_choose);// 蓝色背景
            }
            linearDot.addView(img, layoutParam);
        }
        // 通过适配器引入图片
        MyViewPager mAdapter = new MyViewPager(context, adlist);
        adv_viewpage.setAdapter(mAdapter);
        adv_viewpage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                ADtips[ADCurrentPage]
                        .setBackgroundResource(R.mipmap.homead_nochoose);
                ADCurrentPage = position;
                ADtips[position]
                        .setBackgroundResource(R.mipmap.homead_choose);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        // 计时器
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ADtips[ADCurrentPage]
                                .setBackgroundResource(R.mipmap.homead_nochoose);
                        if (ADCurrentPage == ADtips.length - 1) {
                            ADCurrentPage = 0;
                        } else {
                            ADCurrentPage++;
                        }
                        ADtips[ADCurrentPage]
                                .setBackgroundResource(R.mipmap.homead_choose);
                        adv_viewpage
                                .setCurrentItem(ADCurrentPage);
                    }
                });
            }
        }, 5000, 5000);
        // 轮播图结束
    }


    //    图片数组
    String[] imageViews = { "http://www.zgttyg.com/tiantianyuegou-gm/upload/project/20160912173803_0.jpg", "http://www.zgttyg.com/tiantianyuegou-gm/upload/project/20160905120000_3.jpg",
            " http://www.zgttyg.com/tiantianyuegou-gm/upload/project/20160905115937_0.jpg"};
    class MyViewPager extends PagerAdapter {
        private Context context;
        private List<Ad> data = new ArrayList<>();

        public MyViewPager(Context context, List<Ad> data) {
            this.context = context;
            this.data = data;
            bitmapUtils = new BitmapUtils(context);
        }

        @Override
        public int getCount() {
            return imageViews.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
//            将view添加到container中并将view给返回
            View view = View.inflate(OneGouGoodsDetail.this, R.layout.adapter, null);
            ImageView imageView = (ImageView) view.findViewById(R.id.img);
            bitmapUtils.display(imageView,imageViews[position]);
//            将请求到的图片添加到viewpager中
//            ImageLoader.getInstance().displayImage(imageViews[position], imageView);
            Log.e("图片的地址是========",imageViews[position]);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            super.destroyItem(container, position, object);
            container.removeView((View) object);
        }
    }
*/

//        使用系统的倒计时类

    /**
     * 即使时间类
     */
    class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }
        Activity activity;

        public MyCount(Activity activity, long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            this.activity = activity;
        }
        /**
         * 计时过程
         * @param millisUntilFinished
         */

        @SuppressLint("NewApi")
        @Override
        public void onTick(long millisUntilFinished) {


            Date date = new Date(millisUntilFinished);
            SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
            String str = sdf.format(date);
//            tv_end_time.setText(millisUntilFinished / 1000+"");
            tv_end_time.setText(str);
        }
         /**
         *计时完毕时触发
         */
        @SuppressLint("NewApi")
        @Override
        public void onFinish() {
            tv_end_time.setText("finish");
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        myCount.cancel();
    }
}
